using System;
using System.Collections.Generic;


namespace Framework
{
    public static partial class ReferencePool
    {
        private static readonly Dictionary<Type, ReferenceCollection> s_ReferenceCollections = new Dictionary<Type, ReferenceCollection>();

        public static void ClearAll()
        {
            lock (s_ReferenceCollections)
            {
                foreach (ReferenceCollection referenceCollection in s_ReferenceCollections.Values)
                {
                    referenceCollection.RemoveAll();
                }

                s_ReferenceCollections.Clear();
            }
        }

        public static T Fetch<T>() where T : class, IReference
        {
            return GetReferenceCollection(typeof(T)).Fetch() as T;
        }

        public static IReference Fetch(Type referenceType)
        {
            return GetReferenceCollection(referenceType).Fetch();
        }

        public static void Recycle(IReference reference)
        {
            Type referenceType = reference.GetType();
            GetReferenceCollection(referenceType).Recycle(reference);
        }

        private static ReferenceCollection GetReferenceCollection(Type referenceType)
        {
            ReferenceCollection referenceCollection = null;
            lock (s_ReferenceCollections)
            {
                if (!s_ReferenceCollections.TryGetValue(referenceType, out referenceCollection))
                {
                    referenceCollection = new ReferenceCollection(referenceType);
                    s_ReferenceCollections.Add(referenceType, referenceCollection);
                }
            }
            return referenceCollection;
        }
    }
}